package com.heima.behavior.service.impl;
import java.util.Date;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.model.article.mess.UpdateArticleMess;
import com.heima.model.behavior.dto.ReadBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @author TheCai
 * @date 2021/6/4 22:40
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior>
    implements ApReadBehaviorService {
  @Autowired ApBehaviorEntryService apBehaviorEntryService;
  /**
   * 保存或更新阅读行为
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult readBehavior(ReadBehaviorDto dto) {
    // 1 参数检查
    if (dto == null && dto.getArticleId() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    // 2 查询行为实体 (可能未登录)
    ApBehaviorEntry apBehaviorEntry = null;
    ApUser user = AppThreadLocalUtils.getUser();
    if (user == null || user.getId() == 0) {
      // 设备登录
      apBehaviorEntry= apBehaviorEntryService.findByUserIdOrEquipmentId(null, 0);
    }
    if (user != null && user.getId() != 0) {
      apBehaviorEntry= apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
    }
  if (apBehaviorEntry==null){
    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
  }
    //3 保存或者是更新文章阅读行为
    ApReadBehavior apReadBehavior = this.getOne(Wrappers.<ApReadBehavior>lambdaQuery()
            .eq(ApReadBehavior::getArticleId, dto.getArticleId())
            .eq(ApReadBehavior::getEntryId, apBehaviorEntry.getId()));
    if (apReadBehavior==null){
      //保存阅读行为
      apReadBehavior =  new ApReadBehavior();
      apReadBehavior.setEntryId(apBehaviorEntry.getId());
      apReadBehavior.setArticleId(dto.getArticleId());
      apReadBehavior.setCount(dto.getCount());
      apReadBehavior.setReadDuration(dto.getReadDuration());
      apReadBehavior.setPercentage(dto.getPercentage());
      apReadBehavior.setLoadDuration(dto.getLoadDuration());
      apReadBehavior.setCreatedTime(new Date());
      apReadBehavior.setUpdatedTime(new Date());

      this.save(apReadBehavior);

    }else{
      //     如果有   修改阅读次数  修改更新时间
      apReadBehavior.setCount((short)(apReadBehavior.getCount()+1));
      apReadBehavior.setUpdatedTime(new Date());
      this.updateById(apReadBehavior);

    }
    //计算热点文章消息封装
    UpdateArticleMess updateArticleMess=new UpdateArticleMess();
    updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);//当前是阅读行为
    updateArticleMess.setArticleId(dto.getArticleId());
    updateArticleMess.setAdd(1);//如果阅读文章分值加一,

    kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSONUtil.toJsonStr(updateArticleMess));
    log.info("阅读行为 热点文章计算 消息已发送  消息内容===>> {}",updateArticleMess);

    return ResponseResult.okResult();
  }
  @Autowired
  KafkaTemplate<String,String> kafkaTemplate;
}
